package ssm.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import ssm.dao.ProductDao;
import ssm.pojo.PageBean;
import ssm.pojo.Product;
import util.Dbutil;

import java.sql.SQLException;
import java.util.List;

public class ProductDaoImpl implements ProductDao {
    /**
     * 查询最新的9个商品
     * @return
     * @throws SQLException
     */

    public List<Product> findCateBydate() throws SQLException {
        QueryRunner qr = new QueryRunner(Dbutil.getDataSource());
        String sql = "select * from product order by pdate desc limit 9 ";
        List<Product> list = qr.query(sql, new BeanListHandler<Product>(Product.class));
        return list;
    }

    /**
     * 查询热门商品
     * @return
     * @throws SQLException
     */
    public List<Product> findHotDate() throws SQLException {
        QueryRunner qr = new QueryRunner(Dbutil.getDataSource());
        String sql = "select * from product where is_hot=1 limit 9 ";
        List<Product> list = qr.query(sql, new BeanListHandler<Product>(Product.class));
        return list;
    }

    /**
     * 通过id查询商品
     * @param pid
     * @return
     * @throws SQLException
     */

    public Product findProById(String pid) throws SQLException {
        QueryRunner qr = new QueryRunner(Dbutil.getDataSource());
        String sql = "select * from product where pid = ?";
        Product product = qr.query(sql, new BeanHandler<Product>(Product.class), pid);
        return product;
    }

    /**
     * 查询商品类别的商品总数
     * @param cid 商品类别id
     * @return  总数
     * @throws SQLException
     */
    public int findCountPro(String cid) throws SQLException {
        QueryRunner qr = new QueryRunner(Dbutil.getDataSource());
        String sql = "select count(pid) from product where cid=?";
        Object query = qr.query(sql, new ScalarHandler<>(), cid);
        int i = Integer.parseInt(String.valueOf(query));
        return i;

    }


    /**
     * 分页查询商品页
     * @param nummber 当前页码
     * @param total  每页显示条数
     * @param cid 商品类别
     * @return
     * @throws SQLException
     */
    public List<Product> findProByLimit(int nummber,int total,String cid) throws SQLException {
        QueryRunner qr = new QueryRunner(Dbutil.getDataSource());
        String sql ="select * from product where cid=? limit ?,?";
        List<Product> limitList = qr.query(sql, new BeanListHandler<Product>(Product.class),
                cid,
                (nummber-1)*total,
                total
                );
        return limitList;


    }

//    public static void main(String[] args) throws SQLException {
//        ProductDaoImpl categoryDao = new ProductDaoImpl();
//        int countPro = categoryDao.findCountPro("2");
//        System.out.println(countPro);
//    }
}
